package org.oschina.api.discuss.forum.dao;

import java.util.List;
import org.oschina.Constants;
import org.oschina.api.BaseDAO;
import org.oschina.api.discuss.forum.model.DiscussForum;
import org.oschina.api.discuss.forum.vo.DiscussForumVo;
import org.springframework.stereotype.Repository;

@Repository
public class DiscussForumDAO extends BaseDAO {

	private final String findVo[]={"id","name","`check`","index_type","`index`","create_time"};
	
	/**
	 * 返回
	 * @return
	 */
	public List<DiscussForumVo> findVo()
	{
		return getQueryHelper().query_cache(findVo, null, null, null,DiscussForumVo.class, -1, -1);
	}
	
	/**
	 * 根据ID返回
	 * @param id
	 * @return
	 */
	public DiscussForumVo findVoById(int id)
	{
		DiscussForumVo discussForumVo=(DiscussForumVo)getCacheHelper().hget(getIdKey(id), DiscussForumVo.class);
		if(discussForumVo!=null)
			return discussForumVo;
			
		return _findById(id);
	}
	private DiscussForumVo _findById(int id)
	{
		return (DiscussForumVo) getQueryHelper().queryForObject_cache(findVo, new String[]{"id=?"}, new Object[]{id}, DiscussForumVo.class);
	}
	
	/**
	 * 根据首页类型返回
	 * @param type
	 * @return
	 */
	public List<DiscussForumVo> findByIndexType(int type)
	{
		return getQueryHelper().query_cache(findVo, new String[]{"index_type=?"}, new String[]{"ORDER BY `index`"}, new Object[]{type}, DiscussForumVo.class, -1, -1);
	}
	
	/**
	 * 更新
	 * @param discussForum
	 * @return
	 */
	public int update(DiscussForum discussForum)
	{
		return (int) getQueryHelper().update_cache(new String[]{"name=?","`check`=?","`index`=?","index_type=?"},
				new String[]{"id=?"}, 
				new Object[]{discussForum.getName(),discussForum.getCheck(),discussForum.getIndex(),discussForum.getIndex_type(),discussForum.getId()},DiscussForumVo.class);
	}
	
	/**
	 * 创建
	 * @param discussForum
	 * @return
	 */
	public DiscussForum create(DiscussForum discussForum)
	{
		getQueryHelper().insert_cache(new String[]{"id","name","`check`","index_type","`index`","create_time"}, 
				new Object[]{discussForum.getId(),discussForum.getName(),discussForum.getCheck(),discussForum.getIndex_type(),discussForum.getIndex(),discussForum.getCreate_time()},DiscussForumVo.class);
		return discussForum;
	}
	
	private String getIdKey(Object id)
	{
		return getKey(Constants.CACHE_DISCUSS_FORUM, id);
	}
}